package com.horse.share.twitter;

import java.util.Date;


import oauth.signpost.OAuth;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class TwitterShare extends Activity {
	ProgressDialog myProgressDialog = null;
	private SharedPreferences prefs;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prefs = PreferenceManager.getDefaultSharedPreferences(this);
        if (TwitterUtils.isAuthenticated(prefs)) {
    		sendTweet();
    	} else {
			Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
			i.putExtra("tweet_msg",getTweetMsg());
			startActivity(i);
			finish();
    	}
	}
	
	
	private String getTweetMsg() {
		return "http://www.ises.nl " + new Date().toLocaleString();
	}
	
	private void clearCredentials() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		final Editor edit = prefs.edit();
		edit.remove(OAuth.OAUTH_TOKEN);
		edit.remove(OAuth.OAUTH_TOKEN_SECRET);
		edit.commit();
	}
	
	public void sendTweet() {
		new UpdateTwitterStatusTask().execute();
	}
	
	private class UpdateTwitterStatusTask extends AsyncTask {
        
    	@Override
        protected void onPreExecute(){
    		myProgressDialog = ProgressDialog.show(TwitterShare.this,
                    "Please wait...", 
                    "Updating twitter ...", 
                    true);

        }
        
    	@Override
    	protected void onPostExecute(Object result) 
    	{
    		myProgressDialog.dismiss();
    		if(result == null){
        		Toast.makeText(getBaseContext(), "Twitter updated !", 
        				Toast.LENGTH_SHORT).show();
    		}
    		else{
        		Toast.makeText(getBaseContext(), "\t\tOops !!\nYou can not share duplicate status", 
        				Toast.LENGTH_SHORT).show();
    		}
    		finish();
    	}

		@Override
		protected Object doInBackground(Object... arg0) {
        	try {
        		TwitterUtils.sendTweet(prefs,getTweetMsg());
			} catch (Exception ex) {
				ex.printStackTrace();
				return "fail";
			}
			return null;
		}
    }

	
}
